<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="创建日期">
        <el-date-picker
          v-model="daterangeCreateTime"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="订单编号" prop="serial">
        <el-input
          v-model="queryParams.serial"
          placeholder="请输入订单编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['fm:goodOrder:add']"
        >新增
        </el-button>
      </el-col>
      <!---
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['fm:goodOrder:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['fm:goodOrder:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['fm:goodOrder:export']"
        >导出</el-button>
      </el-col>
      --->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="主键" align="center" prop="id"/>
      <el-table-column label="创建日期" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="订单编号" align="center" prop="serial" v-if="false"/>
      <el-table-column label="金额" align="center" prop="money"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="detail(scope.row)"
            v-hasPermi="['fm:goodOrder:edit']"
          >详情
          </el-button>
          <!--
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['fm:goodOrder:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['fm:goodOrder:remove']"
          >删除</el-button>
          --->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品销售对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <cellGood @end="finishAdd"></cellGood>
      <!---
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="总金额" prop="money">
          <el-input :value="totalMoney" placeholder="请输入金额" disabled />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-divider content-position="center">订单商品详情信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddFmOrderGoodsDetail">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteFmOrderGoodsDetail">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="fmOrderGoodsDetailList" :row-class-name="rowFmOrderGoodsDetailIndex" @selection-change="handleFmOrderGoodsDetailSelectionChange" ref="fmOrderGoodsDetail">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label=" 商品名称" prop="name">
            <template slot-scope="scope">
              <el-autocomplete
                v-model="fmOrderGoodsDetailList[scope.$index].name"
                :fetch-suggestions="queryGoodsAsync"
                value-key="name"
                placeholder="请输入商品名称"
                :trigger-on-focus = "false"
                @select="handleSelectGood($event, scope.$index)"
              >
                <template slot-scope="{ item }">
                  <div >名称：{{ item.name }}</div>
                  <div >价格：{{ item.price }}</div>
                  <div > 库存：{{ item.num }}</div>
                </template>
              </el-autocomplete>
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="prize">
            <template slot-scope="scope">
              <el-input v-model="fmOrderGoodsDetailList[scope.$index].prize" placeholder="请输入单价" />
            </template>
          </el-table-column>
          <el-table-column label="数量" prop="num">
            <template slot-scope="scope">
              <el-input v-model="fmOrderGoodsDetailList[scope.$index].num" placeholder="请输入数量" />
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="notice">
            <template slot-scope="scope">
              <el-input v-model="fmOrderGoodsDetailList[scope.$index].notice" placeholder="请输入备注" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
      --->
    </el-dialog>

    <el-dialog :title="title" :visible.sync="openDetail" width="800px" append-to-body>
      <el-table v-loading="loading" :data="fmOrderGoodsDetailList">
        <el-table-column label=" 商品名称" prop="name" align="center"/>
        <el-table-column label="单价" prop="prize" align="center"/>
        <el-table-column label="数量" prop="num" align="center"/>
        <el-table-column label="备注" prop="notice" align="center"/>
      </el-table>
      <p :style="'float:right'">总计：{{ datail.money }}</p>
      <P></P>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGoodOrder,
  getGoodOrder,
  delGoodOrder,
  addGoodOrder,
  updateGoodOrder,
  exportGoodOrder
} from "@/api/fm/goodOrder";
import {listGoodsByName} from "@/api/fm/goods";
import cellGood from "@/views/fm/goodOrder/sellGood";

export default {
  components: {cellGood},
  name: "GoodOrder",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedFmOrderGoodsDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品销售表格数据
      goodOrderList: [],
      queryGoodList: [],
      datail: {},
      // 订单商品详情表格数据
      fmOrderGoodsDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openDetail: false,
      // 创建日期时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        createTime: null,
        serial: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        serial: [
          {required: true, message: "订单编号不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  computed: {
    totalMoney() {
      let sum = 0;
      for (let i in this.fmOrderGoodsDetailList) {
        sum += this.fmOrderGoodsDetailList[i].prize * this.fmOrderGoodsDetailList[i].num;
      }
      return sum;
      alert(sum);
    }
  },
  methods: {
    /** 查询商品销售列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listGoodOrder(this.queryParams).then(response => {
        this.goodOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    queryGoodsAsync(queryString, cb) {
      if (queryString) {
        listGoodsByName({name: queryString})
          .then(response => cb(response.rows))
          .catch((err) => {
            console.log(err)
          });
      }
    },
    handleSelectGood(item, index) {
      this.fmOrderGoodsDetailList[index].prize = item.price;
    },
    handleSelect(user) {
      this.userId = user.id;
      this.userName = user.custName;
      this.$emit("input", this.userId);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        loginId: null,
        createTime: null,
        serial: null,
        money: null,
        remark: null,
        status: 0
      };
      this.fmOrderGoodsDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品销售";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getGoodOrder(id).then(response => {
        this.form = response.data;
        this.fmOrderGoodsDetailList = response.data.fmOrderGoodsDetailList;
        this.open = true;
        this.title = "修改商品销售";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.money = this.totalMoney;
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.fmOrderGoodsDetailList = this.fmOrderGoodsDetailList;
          if (this.form.id != null) {
            updateGoodOrder(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoodOrder(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除商品销售编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delGoodOrder(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 订单商品详情序号 */
    rowFmOrderGoodsDetailIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 订单商品详情添加按钮操作 */
    handleAddFmOrderGoodsDetail() {
      let obj = {};
      obj.name = "";
      obj.prize = "0";
      obj.num = "1";
      obj.notice = "";
      this.fmOrderGoodsDetailList.push(obj);
    },
    /** 订单商品详情删除按钮操作 */
    handleDeleteFmOrderGoodsDetail() {
      if (this.checkedFmOrderGoodsDetail.length == 0) {
        this.msgError("请先选择要删除的订单商品详情数据");
      } else {
        const fmOrderGoodsDetailList = this.fmOrderGoodsDetailList;
        const checkedFmOrderGoodsDetail = this.checkedFmOrderGoodsDetail;
        this.fmOrderGoodsDetailList = fmOrderGoodsDetailList.filter(function (item) {
          return checkedFmOrderGoodsDetail.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleFmOrderGoodsDetailSelectionChange(selection) {
      this.checkedFmOrderGoodsDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品销售数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportGoodOrder(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    },
    detail(row) {
      this.openDetail = true;
      this.datail = {};
      this.fmOrderGoodsDetailList = [];
      getGoodOrder(row.id).then(response => {
        this.fmOrderGoodsDetailList = response.data.fmOrderGoodsDetailList;
        this.datail.money = row.money;
        this.datail.remark = row.remark;
        this.title = "商品详情";
      })
    },
    finishAdd(msg) {
      this.open = false;
      this.getList();
    }
  }
};
</script>
